package cc.ls51.cms.controller;

import cc.ls51.cms.shiro.ShiroUtils;
import cc.ls51.exception.BusinessException;
import cc.ls51.form.UserLoginForm;
import cc.ls51.modules.SysUser.service.ISysUserService;
import cc.ls51.vo.ResultObject;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author llf
 * @since 2019-08-27
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    ISysUserService sysUserService;

    @PostMapping(value = "/postLogin")
    @ResponseBody
    public ResultObject postLogin(UserLoginForm form) {
        ResultObject ro = ResultObject.ok();
        try {
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(), form.getPassword());
            subject.login(token);
        } catch (AuthenticationException e){
            ro = ResultObject.error(e.getMessage());
        } catch (Exception e){
            ro = ResultObject.error(e.getMessage());
        }
        return ro;
    }
    /**
     * 进入创建用户界面
     *
     * @param model
     * @return
     */
    @GetMapping(value = "/login")
    public String login(Model model, HttpServletRequest request) {
//        model.addAttribute("action", "insert");
//        SysUser sysUser = new SysUser();
//        sysUser.setId(0L);
//        model.addAttribute("sysUser", sysUser);
//        model.addAttribute("roles", sysRoleService.ListSysRoleUseable());
//        model.addAttribute("url", request.getContextPath() + "/sys/user/");
        return "/SysUser/login";
    }
}
